package com.rock.platform.util;

import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;

public class SessionUtils {

	public static final String SKEY_LOGINNAME = "SYS_LOGINNAME";
	public static final String SKEY_USERID = "SYS_USERID";
	public static final String SKEY_USERCODE = "SYS_USERCODE";
	public static final String SKEY_USERNAME = "SYS_USERNAME";
	public static final String SKEY_USERAUTH = "SYS_USERAUTH";
	public static final String SKEY_LOGINTIME = "SYS_LOGINTIME";
	public static final String SKEY_LANGUAGE = "SYS_LANGUAGE";
	public static final String SKEY_REMOTEHOST = "SYS_REMOTEHOST";
	public static final String SKEY_REMOTEIP = "SYS_REMOTEIP";
	public static final String SKEY_TOKENID = "SYS_TOKENID";

	public static final String SKEY_LOGINBEAN = "SYS_LOGINBEAN";
	
	private static HttpSession getSession() {
		return ServletActionContext.getRequest().getSession();
	}

	public static Object getAttribute(String key) {
		return getSession().getAttribute(key);
	}

	public static String getAttributeText(String key) {
		Object o = getAttribute(key);

		return ((o != null) ? o.toString() : "");
	}

	public static void setAttribute(String key, Object value) {
		getSession().setAttribute(key, value);
	}

	public static void removeAttribute(String key) {
		getSession().removeAttribute(key);
	}

	public static void invalidate() {
		getSession().invalidate();
	}

	public static LoginBean getLoginBean() {
		HttpSession session = getSession();

		Object oLoginBean = session.getAttribute(SKEY_LOGINBEAN);
		if (oLoginBean != null) return (LoginBean)oLoginBean;
		
		Object oLoginName = session.getAttribute(SKEY_LOGINNAME);
		Object oUserId = session.getAttribute(SKEY_USERID);
		Object oUserCode = session.getAttribute(SKEY_USERCODE);
		Object oUserName = session.getAttribute(SKEY_USERNAME);
		Object oUserAuth = session.getAttribute(SKEY_USERAUTH);

		Object oLoginTime = session.getAttribute(SKEY_LOGINTIME);
		Object oLanguage = session.getAttribute(SKEY_LANGUAGE);

		Object oRemoteHost = session.getAttribute(SKEY_REMOTEHOST);
		Object oRemoteIp = session.getAttribute(SKEY_REMOTEIP);
		Object oTokenId = session.getAttribute(SKEY_TOKENID);

		LoginBean loginBean = new LoginBean(
							(oLoginName != null) ? oLoginName.toString() : "",
							(oUserId != null) ? oUserId.toString() : "",
							(oUserCode != null) ? oUserCode.toString() : "",
							(oUserName != null) ? oUserName.toString() : "",
							(oUserAuth != null) ? oUserAuth.toString() : "",
							(oLoginTime != null) ? oLoginTime.toString() : "",
							(oLanguage != null) ? oLanguage.toString() : "",
							(oRemoteHost != null) ? oRemoteHost.toString() : "",
							(oRemoteIp != null) ? oRemoteIp.toString() : "",
							(oTokenId != null) ? oTokenId.toString() : "");
		session.setAttribute(SKEY_LOGINBEAN, loginBean);
		
		return loginBean;
	}
}
